//
//  ziXunViewController.m
//  中关村在线
//
//  Created by hy on 16/1/9.
//  Copyright © 2016年 hongyu. All rights reserved.
//

#import "ziXunViewController.h"
#import "heatCollectionViewCell.h"
#import "hyTableViewCell.h"
#import "zixunModel.h"
#import "UIImageView+WebCache.h"
#import "NetWorkHandker.h"
#import "lunbomodel.h"
#import "DCPicScrollView.h"
#import "DCWebImageManager.h"
#import "NewTableViewCell.h"
#import "newOneTableViewCell.h"
#import "newTwoTableViewCell.h"
@interface ziXunViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>
@property (nonatomic, retain) UICollectionView *collection;
@property (nonatomic, retain) UIScrollView *scroll;
@property (nonatomic, retain) NSMutableArray *modelArr;
@property (nonatomic, retain) NSMutableArray *appleModelArray;
@property (nonatomic, retain) NSMutableArray *newsMidelArray;
@property (nonatomic, retain) NSMutableArray *lunboArr;
@property (nonatomic, retain) UITableView *table;
@property (nonatomic, retain) UITableView *table1;
@property (nonatomic, retain) UITableView *appleTable;
@property (nonatomic, retain) NSString *str;
@property (nonatomic, retain) UITableView *table2;
@property (nonatomic, retain) UIScrollView *headerView;
@property (nonatomic, retain) NSMutableArray *newsCellArray;
@end
int a = 1;
@implementation ziXunViewController

- (void)dealloc {
    [_newsCellArray release];
    [_table2 release];
    [_appleTable release];
    [_appleModelArray release];
    [_headerView release];
    [_str release];
    [_table release];
    [_table1 release];
    [_lunboArr release];
    [_modelArr release];
    [_collection release];
    [_scroll release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationController.navigationBar.hidden = YES;
    self.navigationController.navigationBar.barStyle = UIStatusBarStyleLightContent;
    [self creatcollction];
    [self button];
//  创建滚动视图
    [self creatscrollView];
//  数据解析
    [self jiexi];
//  第二页
    [self creater];
//  创建第三页 苹果
    [self creatApple];
//  创建第四页 新闻
    [self creatNews];
}

- (void)creatcollction {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.itemSize = CGSizeMake(40, 40);
    layout.minimumInteritemSpacing = 5;
//    layout.minimumLineSpacing = 5;
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(10, 20, 300, 40) collectionViewLayout:layout];
    _collection.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_collection];
    [_collection release];
    _collection.showsHorizontalScrollIndicator = NO;
    [layout release];
    _collection.delegate = self;
    _collection.dataSource = self;
    [_collection registerClass:[heatCollectionViewCell class]forCellWithReuseIdentifier:@"cell"];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 12;
   }
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

        heatCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor clearColor];
    NSArray *array = @[@"头条", @"订阅", @"苹果", @"新闻", @"手机", @"评测", @"数码", @"电脑", @"热榜", @"导购", @"视频", @"平板"];
        cell.wenziLabel.text = array[indexPath.row];
        cell.wenziLabel.font = [UIFont systemFontOfSize:17];
        cell.wenziLabel.textColor = [UIColor whiteColor];
        cell.wenziLabel.tag = 1000 + indexPath.row;
        return cell;
}

// collectionView的点击方法  点击第一次放大
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"%@", indexPath);
    
    UILabel *label = [_collection viewWithTag:1000 + indexPath.row];
    label.font = [UIFont systemFontOfSize:20];
//    创建视图2 订阅
    if (indexPath.row == 1) {
        _scroll.contentOffset = CGPointMake(375, 0);
        }
    else if (indexPath.row == 0) {
        _scroll.contentOffset = CGPointMake(0, 0);
    }
    else if (indexPath.row == 2) {
        _scroll.contentOffset = CGPointMake(2 * 375, 0);
    }
    else if (indexPath.row == 3) {
        _scroll.contentOffset = CGPointMake(3 * 375, 0);
    }
}

//点击第二次缩小
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
    UILabel *label = [_collection viewWithTag:1000 + indexPath.row];
    label.font = [UIFont systemFontOfSize:17];
}
- (void)button {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.backgroundColor = [UIColor clearColor];
    button.frame = CGRectMake(330, 33, 20, 20);
    [button setImage:[UIImage imageNamed:@"bai2.png"] forState:UIControlStateNormal];
    [self.view addSubview:button];
}
//创建滚动视图
- (void)creatscrollView {
    self.scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 60, 375, 607)];
    _scroll.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_scroll];
    _scroll.contentSize = CGSizeMake(375 * 12, 0);
    _scroll.pagingEnabled = YES;
     [self tableView];
}



- (void)tableView {
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 110) style:UITableViewStylePlain];
    _table.rowHeight = 80;
    [_scroll addSubview:_table];
    _table.delegate = self;
    _table.dataSource = self;
    [_table registerNib:[UINib nibWithNibName:@"hyTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"cell"];
//    轮播头视图
    [self lunbo];
}
#pragma mark table degetage
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == _table) {
        return _modelArr.count;
    }
    else if (tableView == _appleTable) {
        return _appleModelArray.count;
    }
    else if (tableView == _table2) {
        return _newsCellArray.count;
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == _table) {
        hyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        zixunModel *model = _modelArr[indexPath.row];
        [cell.hyimage sd_setImageWithURL:[NSURL URLWithString:model.imgsrc] placeholderImage:[UIImage imageNamed:@"3.png"]];
        cell.lable1.text = model.stitle;
        cell.lable1.numberOfLines = 2;
        NSString *str = [model.sdate substringWithRange:NSMakeRange(6, 1)];
        NSString *str1 = [model.sdate substringWithRange:NSMakeRange(8, 2)];
        
        cell.lable2.text = [NSString stringWithFormat:@"%@-%@", str, str1];
        cell.lable2.textColor = [UIColor grayColor];
        cell.lable2.font = [UIFont systemFontOfSize:13];
        cell.lable3.text = [NSString stringWithFormat:@"%@", model.comment_num];
        cell.lable3.textColor = [UIColor grayColor];
        cell.lable3.font = [UIFont systemFontOfSize:13];
        return cell;
    }
    else if (tableView == _appleTable) {
        hyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        zixunModel *model = _appleModelArray[indexPath.row];
        [cell.hyimage sd_setImageWithURL:[NSURL URLWithString:model.imgsrc]];
        cell.lable1.text = model.stitle;
        cell.lable1.numberOfLines = 2;
        NSString *str = model.sdate;
        NSString *str1 = [str substringWithRange:NSMakeRange(6, 1)];
        NSString *str2 = [str substringWithRange:NSMakeRange(8, 2)];
        cell.lable2.text = [NSString stringWithFormat:@"%@-%@",str1, str2];
        cell.lable2.textColor = [UIColor grayColor];
        cell.lable2.font = [UIFont systemFontOfSize:13];
        cell.lable3.text = [NSString stringWithFormat:@"%@", model.comment_num];
        cell.lable3.font = [UIFont systemFontOfSize:13];
        cell.lable3.textColor = [UIColor grayColor];
        return cell;
    }
//    如果是我的新闻页table
    else if (tableView == _table2) {
        zixunModel *model = _newsCellArray[indexPath.row];
        NSMutableArray *array = model.pics;
        if (array.count == 0) {
            newOneTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"newOneCell" forIndexPath:indexPath];
            NSString *str = model.sdate;
            NSString *str1 = [str substringWithRange:NSMakeRange(11, 5)];
            cell.timeLabel.text = str1;
            cell.timeLabel.textColor = [UIColor grayColor];
            cell.timeLabel.font = [UIFont systemFontOfSize:13];
            cell.tilteLabel.text = model.stitle;
            cell.tilteLabel.numberOfLines = 2;
            cell.talkLabel.text = [NSString stringWithFormat:@"%@评论", model.comment_num];
            cell.talkLabel.textColor = [UIColor grayColor];
            cell.talkLabel.font = [UIFont systemFontOfSize:13];
            return cell;
        }
        else if (array.count == 1) {
            NewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"newcell" forIndexPath:indexPath];
            [cell.tupian sd_setImageWithURL:[NSURL URLWithString:model.imgsrc]];
            NSString *time = model.sdate;
            NSString *newTime = [time substringWithRange:NSMakeRange(11, 5)];
            cell.timeLabel.text = newTime;
            cell.timeLabel.textColor = [UIColor grayColor];
            cell.timeLabel.font = [UIFont systemFontOfSize:13];
            cell.titleLabel.text = model.stitle;
            cell.titleLabel.numberOfLines = 2;
            cell.talkLabel.text = [NSString stringWithFormat:@"%@评论", model.comment_num];
            cell.talkLabel.textColor = [UIColor grayColor];
            cell.talkLabel.font = [UIFont systemFontOfSize:13];
            return cell;
        }
        else if (array.count > 1) {
            newTwoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"newTwoCell" forIndexPath:indexPath];
            NSString *time = model.sdate;
            NSString *time1 = [time substringWithRange:NSMakeRange(11, 5)];
            cell.timelabel.text = time1;
            cell.timelabel.textColor = [UIColor grayColor];
            cell.timelabel.font = [UIFont systemFontOfSize:13];
            cell.titlelable.text = model.stitle;
            cell.titlelable.numberOfLines = 2;
            [cell.image1 sd_setImageWithURL:[NSURL URLWithString:array[0]]];
            [cell.image2 sd_setImageWithURL:[NSURL URLWithString:array[1]]];
            [cell.image3 sd_setImageWithURL:[NSURL URLWithString:array[2]]];
            
            return cell;
        }
    }
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == _table2) {
        zixunModel *model = _newsCellArray[indexPath.row];
        NSMutableArray *array = model.pics;
        if (array.count > 1) {
            return 140;
        }
        else {
            return 80;
        }
    }
    else if (tableView == _table) {
        return 80;
    }
    else if (tableView == _appleTable) {
        return 80;
    }
    return 0;
}

- (void)jiexi {
    [NetWorkHandker GETRequestWithString:@"http://lib.wap.zol.com.cn/ipj/docList/?v=6.0&class_id=0&page=1&vs=and412&retina=1&last_time=2016-01-09%2013:47" completion:^(id result) {
        NSData *data = result;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                    NSMutableArray *arr = dic[@"list"];
                    self.modelArr = [NSMutableArray array];
                    for (NSDictionary *dic in arr) {
                        zixunModel *model = [zixunModel zixun];
                        [model setValuesForKeysWithDictionary:dic];
                        [_modelArr addObject:model];
                    }
        
        [_table reloadData];
    }];
}
- (void)lunbo {
    UIView *touview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 375, 200)];
    _table.tableHeaderView = touview;
    [touview release];
    [NetWorkHandker GETRequestWithString:@"http://lib.wap.zol.com.cn/ipj/docList/?v=6.0&class_id=0&page=1&vs=and412&retina=1&last_time=2016-01-09%2013:47" completion:^(id result) {
        NSData *data = result;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray *arr2 = dic[@"pics"];
        self.lunboArr = [NSMutableArray array];
        for (NSDictionary *dic in arr2) {
            lunbomodel *model = [lunbomodel lunbo];
            [model setValuesForKeysWithDictionary:dic];
            [_lunboArr addObject:model];
        }
        [_table reloadData];
        self.headerView = [[UIScrollView alloc] initWithFrame:touview.bounds];
        _headerView.contentSize = CGSizeMake(touview.frame.size.width * 7, 0);
        _headerView.backgroundColor = [UIColor whiteColor];
        _headerView.pagingEnabled = YES;
//        _headerView.contentOffset = CGPointMake(375, 0);
        _headerView.showsHorizontalScrollIndicator = NO;
        _headerView.delegate = self;
        [touview addSubview:_headerView];
        [_headerView release];
        NSMutableArray *array = [NSMutableArray array];
        for (lunbomodel *model in _lunboArr) {
            self.str = model.imgsrc;
            [array addObject:_str];
        }
        for (NSInteger i = 2; i < 7; i++) {
            UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(375 * (i - 1), 0, 375, 200)];
            [_headerView addSubview:image];
            [image sd_setImageWithURL:[NSURL URLWithString:array[i - 2]]];
        }
        UIImageView *image1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 375, 200)];
        [image1 sd_setImageWithURL:[NSURL URLWithString:array[4]]];
        [_headerView addSubview:image1];
        UIImageView *image2 = [[UIImageView alloc] initWithFrame:CGRectMake(375 * 6, 0, 375, 200)];
        [image2 sd_setImageWithURL:[NSURL URLWithString:array[0]]];
        [_headerView addSubview:image2];
    }];
    
    [NSTimer scheduledTimerWithTimeInterval:100000 target:self selector:@selector(zidong:) userInfo:nil repeats:YES];
}
- (void)zidong:(UIScrollView *)scroll {
//   用点跳
//    _headerView.contentOffset = CGPointMake((a % 5) * _headerView.frame.size.width, 0);
//   平推自动
    [_headerView setContentOffset:CGPointMake((a % 5 + 1) * _headerView.frame.size.width, 0) animated:YES];
    a++;
}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (_headerView.contentOffset.x == 375 * 6) {
        _headerView.contentOffset = CGPointMake(375, 0);
    }
        if (_headerView.contentOffset.x == 0) {
            _headerView.contentOffset = CGPointMake(375 * 5, 0);
        }
}


//创建第二页
- (void)creater {
    self.table1 = [[UITableView alloc] initWithFrame:CGRectMake(375, 40, _scroll.frame.size.width, _scroll.frame.size.height) style:UITableViewStylePlain];
    _table1.separatorStyle = UITableViewCellSeparatorStyleNone;
    _table1.backgroundColor = [UIColor colorWithRed:241 / 255.0 green:241 / 255.0 blue:241 / 255.0 alpha:1];
    [_scroll addSubview:_table1];
    [_table1 release];
    //        数据解析
//    [self Date];
    //        添加更多精彩订阅
    [self addMoreNews];
}




//视图2 订阅数据解析  POST请求数据没找到
- (void)Date {
//    {"lisType":2,"media_ids":"5,1,4,6,11","version":"iph442"}
    NSString *string = @"http://lib.wap.zol.com.cn/ipj/rss/rssList/?v=3.0";
    NSString *newStr = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:string]];
    NSURL *url = [NSURL URLWithString:newStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    request.HTTPMethod = @"POST";
    NSDictionary *dic = @{@"lisType":@2,@"version":@"iph442",@"ssid":@"$2a$10$7f8fcfad3c754ecfc98e6a3bcfccae1fc6b5e987d0ad1ed1fcdb9b4a0aa34223"};
    NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
    request.HTTPBody = data;
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"44444444%@", dic);
        });
    }];
    [task resume];
}
//更多精彩订阅
- (void)addMoreNews {
    UIButton *addMoreButton = [UIButton buttonWithType:UIButtonTypeCustom];
    addMoreButton.frame = CGRectMake(375, 0, 375, 40);
    [addMoreButton setTitle:@"❤︎添加更多精彩订阅" forState:UIControlStateNormal];
    addMoreButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [addMoreButton setTitleColor:[UIColor colorWithRed:0 / 255.0 green:127 / 255.0 blue:250 / 255.0 alpha:1] forState:UIControlStateNormal];
    [_scroll addSubview:addMoreButton];
}
//第三页苹果
- (void)creatApple {
    self.appleTable = [[UITableView alloc] initWithFrame:CGRectMake(375 * 2, 0, _scroll.frame.size.width, _scroll.frame.size.height) style:UITableViewStylePlain];
    _appleTable.rowHeight = 80;
    [_scroll addSubview:_appleTable];
    [_appleTable release];
    _appleTable.delegate = self;
    _appleTable.dataSource = self;
    [_appleTable registerNib:[UINib nibWithNibName:@"hyTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"cell"];
    [self appleData];
}

- (void)appleData {
    [NetWorkHandker GETRequestWithString:@"http://lib.wap.zol.com.cn/ipj/docList/?v=6.0&class_id=255&isReviewing=NO&last_time=2016-01-12%2019%3A49&page=1&retina=1&vs=iph442" completion:^(id result) {
        NSData *data = result;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray *array = dic[@"list"];
        self.appleModelArray = [NSMutableArray array];
        for (NSDictionary *dic in array) {
            zixunModel *model = [zixunModel zixun];
            [model setValuesForKeysWithDictionary:dic];
            [_appleModelArray addObject:model];
        }
        [_appleTable reloadData];
    }];
}

- (void)creatNews {

    self.table2 = [[UITableView alloc] initWithFrame:CGRectMake(3 * 375, 0, _scroll.frame.size.width, _scroll.frame.size.height - 49) style:UITableViewStylePlain];
    _table2.rowHeight = 80;
    _table2.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_scroll addSubview:_table2];
    [_table2 release];
    _table2.delegate = self;
    _table2.dataSource = self;
    [_table2 registerNib:[UINib nibWithNibName:@"NewTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"newcell"];
    [_table2 registerNib:[UINib nibWithNibName:@"newOneTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"newOneCell"];
    [_table2 registerNib:[UINib nibWithNibName:@"newTwoTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"newTwoCell"];
    //    解析数据
    [self newslb];
}
- (void)newslb {
   
    [NetWorkHandker GETRequestWithString:@"http://lib.wap.zol.com.cn/ipj/docList/?v=6.0&class_id=1&isReviewing=NO&last_time=2016-01-12%2022%3A33&page=1&retina=1&vs=iph442" completion:^(id result) {
           NSData *data = result;
           NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//        轮播图图片
           NSArray *arr = dic[@"pics"];
          self.newsMidelArray = [NSMutableArray array];
           for (NSDictionary *dic in arr) {
               zixunModel *model = [zixunModel zixun];
               [model setValuesForKeysWithDictionary:dic];
               [_newsMidelArray addObject:model];
               [self creatNewHeatView];
           }
//        页面数据个数
        NSArray *arr1 = dic[@"list"];
        self.newsCellArray = [NSMutableArray array];
        for (NSDictionary *dic in arr1) {
            zixunModel *model = [zixunModel zixun];
            [model setValuesForKeysWithDictionary:dic];
            [_newsCellArray addObject:model];
        }
        [_table2 reloadData];
    }];
}
- (void)creatNewHeatView {
    NSMutableArray *urlarray = [NSMutableArray array];
    for (zixunModel *model in _newsMidelArray) {
        NSString *new = model.imgsrc;
        [urlarray addObject:new];
    }
    NSLog(@"%@", urlarray);
    DCPicScrollView *pic = [DCPicScrollView picScrollViewWithFrame:CGRectMake(0, 0, 375, 200) WithImageUrls:urlarray];
    pic.AutoScrollDelay = 3.0;
    _table2.tableHeaderView = pic;
    NSMutableArray *titleArray = [NSMutableArray array];
    for (zixunModel *model in _newsMidelArray) {
        NSString *title = model.stitle;
        [titleArray addObject:title];
    }
    //    显示文字
    //    pic.titleData = titleArray;
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 5, 100, 30);
    [button setTitle:@"今日最热" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_table2 addSubview:button];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation
 
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
